//
//  EFAMoreInfoVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/7/12.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAMoreInfoVC.h"
#import "EFAMoreInfoTCell.h"
#import "EFAMoreNameVC.h"
#import <TZImagePickerController.h>
#import "ApiManager.h"
#import "XDQiniuManager.h"
#import "EFAModel.h"
#import "GlobalHeader.h"
#import <UIImageView+WebCache.h>
#import "EFAMoreMdyPwdVC.h"

@interface EFAMoreInfoVC ()<UITableViewDelegate, UITableViewDataSource, TZImagePickerControllerDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSArray *dataArray;
@end

static NSString *const kReuseCellId = @"EFAMoreInfoTCell";

@implementation EFAMoreInfoVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.dataArray = nil;
    [self refreshWholeView];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initNavigationBar {
    self.navigationItem.title = @"个人资料";
}

- (void)initSubViews {
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    //    self.tableView.tableFooterView = [UIView new];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EFAMoreInfoTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    if(indexPath.row < self.dataArray.count) {
        NSDictionary *dic = self.dataArray[indexPath.row];
        cell.leftTitleLabel.text = dic[@"title"];
        cell.portraitImgView.image = [UIImage imageNamed:dic[@"imgName"]];
        NSString *headerImgUrl = [EFAModel sharedInstance].loginInfo.user_info.efairyuser_headimg_url;
        [cell.portraitImgView sd_setImageWithURL:[NSURL URLWithString:headerImgUrl ? headerImgUrl : @""] placeholderImage:[UIImage imageNamed:dic[@"imgName"]]];
        cell.portraitImgView.hidden = ![dic[@"imgName"] length];
        cell.rightTitleLabel.text = dic[@"subTitle"];
        cell.rightTitleLabel.hidden = ![dic[@"subTitle"] length];
        cell.rightArrowImgView.hidden = ![dic[@"arrow"] boolValue];
    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 14.9;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.dataArray.count) {
        NSDictionary *dic = self.dataArray[indexPath.row];
        return [dic[@"rowHeight"] floatValue];
    }
    return 45.0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row < self.dataArray.count) {
        NSDictionary *dic = self.dataArray[indexPath.row];
        if ([dic[@"title"] isEqualToString:@"头像"]) {
            [self modifyPortrait];
        } else if ([dic[@"title"] isEqualToString:@"昵称"]) {
            [self jumpToEditName];
        } else if ([dic[@"title"] isEqualToString:@"修改密码"]) {
            [self jumpToModifyPwd];
        }
    }
    
//    if (indexPath.row == 0) {
//        [self modifyPortrait];
//    } else if (indexPath.row == 1) {   //!< 修改昵称
//        [self jumpToEditName];
//    } else if (indexPath.row == 2) {
//        [self jumpToModifyPwd];
//    }
}

// 选择图片成功调用此方法
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    // dismiss UIImagePickerController
    [picker dismissViewControllerAnimated:YES completion:nil];
    // 选择的图片信息存储于info字典中
    NSLog(@"%@", info);
    
    //通过UIImagePickerControllerMediaType判断返回的是照片还是视频
    NSString* type = [info objectForKey:UIImagePickerControllerMediaType];
    //如果返回的type等于kUTTypeImage，代表返回的是照片,并且需要判断当前相机使用的sourcetype是拍照还是相册
    if ([type isEqualToString:(NSString*)kUTTypeImage]) {
        //获取图片裁剪的图
        UIImage* edit = [info objectForKey:UIImagePickerControllerEditedImage];
        [self uploadImageToQiniuWithHeaderImg:edit];
    }
}


// 取消图片选择调用此方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    // dismiss UIImagePickerController
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - event response
#pragma mark - private methods
- (void)modifyPortrait {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self selectImgFromSourceType:UIImagePickerControllerSourceTypeCamera];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self selectImgFromSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)selectImgFromSourceType:(UIImagePickerControllerSourceType)sourceType {
    // 判断当前的sourceType是否可用
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        return;
    }
    // 实例化UIImagePickerController控制器
    UIImagePickerController * imagePickerVC = [[UIImagePickerController alloc] init];
    // 设置资源来源（相册、相机、图库之一）
    imagePickerVC.sourceType = sourceType;
    // 如果选择的是视屏，允许的视屏时长为20秒
    imagePickerVC.videoMaximumDuration = 20;
    // 允许的视屏质量（如果质量选取的质量过高，会自动降低质量）
    imagePickerVC.videoQuality = UIImagePickerControllerQualityTypeHigh;
    // 设置可用的媒体类型、默认只包含kUTTypeImage，如果想选择视频，请添加kUTTypeMovie
    imagePickerVC.mediaTypes = @[(NSString *)kUTTypeImage];
    // 设置代理，遵守UINavigationControllerDelegate, UIImagePickerControllerDelegate 协议
    imagePickerVC.delegate = self;
    // 是否允许编辑（YES：图片选择完成进入编辑模式）
    imagePickerVC.allowsEditing = YES;
    // model出控制器
    [self presentViewController:imagePickerVC animated:YES completion:nil];
}

- (void)uploadImageToQiniuWithHeaderImg:(UIImage *)headerImage {
    if (!headerImage) {
        return;
    }
    
    // 上传图片
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.progress = 0;
    hud.label.text = @"上传图片...";
    [[XDQiniuManager sharedInstance] uploadImages:@[headerImage] progress:^(NSString *key, float percent) {
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.progress = percent;
        });
    } success:^(NSArray<NSString *> *urlArray) {
        [hud hideAnimated:NO];
        // 发表到服务器
        NSString *name = [EFAModel sharedInstance].loginInfo.user_info.efairyuser_nickname;
        [self requestEditUserInfoWithHeadImgUrl:urlArray.firstObject name:name];
        NSLog(@"开始发表到服务器");
    } failure:^(NSString *error) {
        NSLog(@"上传图片失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:error];
    }];
}

- (void)jumpToEditName {
    EFAMoreNameVC *vc = [[EFAMoreNameVC alloc] init];
    vc.curType = EFAMoreNameTypeName;
    [self showViewController:vc sender:nil];
}

- (void)jumpToEditCompany {
    EFAMoreNameVC *vc = [[EFAMoreNameVC alloc] init];
    vc.curType = EFAMoreNameTypeCompany;
    [self showViewController:vc sender:nil];
}

- (void)jumpToEditCompanyAddress {
    EFAMoreNameVC *vc = [[EFAMoreNameVC alloc] init];
    vc.curType = EFAMoreNameTypeCompanyAddress;
    [self showViewController:vc sender:nil];
}

- (void)jumpToEditEmail {
    EFAMoreNameVC *vc = [[EFAMoreNameVC alloc] init];
    vc.curType = EFAMoreNameTypeEmail;
    [self showViewController:vc sender:nil];
}

- (void)jumpToModifyPwd {
    UIStoryboard *mainSb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    EFAMoreMdyPwdVC *vc = [mainSb instantiateViewControllerWithIdentifier:@"EFAMoreMdyPwdVC"];
    [self showViewController:vc sender:nil];
}

- (void)refreshWholeView {
    [self.tableView reloadData];
}

#pragma mark - network request
- (void)requestEditUserInfoWithHeadImgUrl:(NSString *)headimg_url name:(NSString *)name {
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    headimg_url = headimg_url ? headimg_url : [EFAModel sharedInstance].loginInfo.user_info.efairyuser_headimg_url;
    name = name ? name : [EFAModel sharedInstance].loginInfo.user_info.efairyuser_nickname;
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairyuser_headimg_url" : headimg_url ? headimg_url : @"",
                           @"efairyuser_nickname" : name ? name : @""};
    
    [[XDAFNetworking sharedInstance] PUT:[ApiManager apiMineUserCenter] parameters:pars success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"修改个人信息成功：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[EFAGlobalJsonKeyErrCode] integerValue] == 200) {
            [EFAModel sharedInstance].loginInfo.user_info.efairyuser_nickname = name;
            [EFAModel sharedInstance].loginInfo.user_info.efairyuser_headimg_url = headimg_url;
            [self refreshWholeView];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"修改个人信息失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (NSArray *)dataArray {
    if (!_dataArray) {
        EFALoginUserInfo *userInfo = [EFAModel sharedInstance].loginInfo.user_info;
        NSString *nickName = userInfo.efairyuser_nickname ? userInfo.efairyuser_nickname : @"";
        _dataArray = @[@{@"title" : @"头像",
                         @"subTitle" : @"",
                         @"imgName" : @"global_portrait",
                         @"rowHeight" : @(67),
                         @"arrow" : @(YES)},
                       @{@"title" : @"昵称",
                         @"subTitle" : nickName,
                         @"imgName" : @"",
                         @"rowHeight" : @(45),
                         @"arrow" : @(YES)},
                       @{@"title" : @"修改密码",
                         @"subTitle" : @"",
                         @"imgName" : @"",
                         @"rowHeight" : @(45),
                         @"arrow" : @(YES)}];
        
        
//        @{@"title" : @"单位名称",
//          @"subTitle" : company,
//          @"imgName" : @"",
//          @"rowHeight" : @(45),
//          @"arrow" : @(YES)},
//        @{@"title" : @"单位地址",
//          @"subTitle" : address,
//          @"imgName" : @"",
//          @"rowHeight" : @(45),
//          @"arrow" : @(YES)},
//        @{@"title" : @"联系电话",
//          @"subTitle" : phone,
//          @"imgName" : @"",
//          @"rowHeight" : @(45),
//          @"arrow" : @(NO)},
//        @{@"title" : @"联系邮箱",
//          @"subTitle" : email,
//          @"imgName" : @"",
//          @"rowHeight" : @(45),
//          @"arrow" : @(YES)},
//        @{@"title" : @"设备供应商",
//          @"imgName" : @"",
//          @"subTitle" : supplier,
//          @"rowHeight" : @(45),
//          @"arrow" : @(NO)},
    }
    return _dataArray;
}

@end
